
// #ifndef VUE3
import Vue from 'vue'
import App from './App'
import store from './store'


// 简单的全局登录拦截器
function setupAuthGuard() {
    const whiteList = [
        '/fk/LoginPage/index',
        '/fk/RegisterPage/index'
    ]

    const isWhite = (url) => {
        if (!url) return false
        // 统一转成以 / 开头的路径
        const path = url.startsWith('/') ? url.split('?')[0] : ('/' + url.split('?')[0])
        return whiteList.includes(path)
    }

    const hasToken = () => {
        try {
            return !!(uni.getStorageSync('token') || uni.getStorageSync('Authorization'))
        } catch (e) {
            return false
        }
    }

    const guard = {
        invoke(args) {
            const url = args && (args.url || args)
            if (isWhite(url) || hasToken()) {
                return true
            }
            // 未登录，拦截并跳到登录页
            uni.reLaunch({ url: '/fk/LoginPage/index' })
            return false
        }
    }

    try {
        uni.addInterceptor('navigateTo', guard)
        uni.addInterceptor('redirectTo', guard)
        uni.addInterceptor('reLaunch', guard)
        uni.addInterceptor('switchTab', guard)
    } catch (e) {
        console.error('注册全局拦截器失败：', e)
    }
}

setupAuthGuard()

// 全局请求拦截：自动附带 token 与 userId
function setupRequestInterceptor() {
    const getAuthHeader = () => {
        try {
            if (store && store.getters && store.getters.authHeader) return store.getters.authHeader
        } catch (e) {}
        try { return uni.getStorageSync('Authorization') || '' } catch (e) { return '' }
    }
    const getUserId = () => {
        try { return (store && store.state && store.state.userId) || uni.getStorageSync('userId') || '' } catch (e) { return '' }
    }

    const attachAuth = (args) => {
        const token = getAuthHeader()
        const userId = getUserId()
        args.header = Object.assign({}, args.header || {},
            token ? { Authorization: token } : {},
            userId ? { 'X-User-Id': userId, 'userId': userId } : {}
        )
        return args
    }

    try {
        uni.addInterceptor('request', { invoke: attachAuth })
        uni.addInterceptor('uploadFile', { invoke: attachAuth })
    } catch (e) {
        console.error('注册请求拦截器失败：', e)
    }
}

setupRequestInterceptor()


Vue.config.productionTip = false

App.mpType = 'app'

const app = new Vue({
    store,
    ...App
})
app.$mount()
// #endif

// #ifdef VUE3
import { createSSRApp } from 'vue'
import App from './App.vue'
export function createApp() {
  const app = createSSRApp(App)
  // VUE3 模式同样注册拦截
  try { setupAuthGuard() } catch (e) {}
  return {
    app
  }
}
// #endif